<template>
  <div class="page-register">
    <article class="header">
      <header>
        <nuxt-link to="/" class="site-logo" />
        <span class="login">
          <em class="bold">已有美团账号？</em>
          <a href="/login">
            <el-button type="primary" size="small">登录</el-button>
          </a>
        </span>
      </header>
    </article>
    <section>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="昵称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-button size="mini" round @click="sendMsg">
            发送验证码
          </el-button>
          <span class="status">{{ statusMsg }}</span>
          <el-input v-model="ruleForm.code" maxlength="4" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="ruleForm.pwd" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="cpwd">
          <el-input v-model="ruleForm.cpwd" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button class="register" type="primary" @click="register">
            同意以下协议并注册
          </el-button>
          <div class="error">
            {{ error }}
          </div>
        </el-form-item>
        <el-form-item>
          <a
            class="f1"
            href="http://www.meituan.com/about/terms"
            target="_blank"
          >《美团网用户协议》</a>
        </el-form-item>
      </el-form>
    </section>
  </div>
</template>

<script>
import CryptoJs from 'crypto-js'
export default {
  data () {
    return {
      statusMsg: '',
      error: '',
      ruleForm: {
        name: '',
        code: '',
        pwd: '',
        cpwd: '',
        email: ''
      },
      rules: {
        name: [
          {
            required: true,
            type: 'string',
            message: '请输入昵称',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            type: 'email',
            message: '请输入邮箱',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            type: 'string',
            message: '请输入验证码',
            min: 4,
            max: 4,
            trigger: 'blur'
          }
        ],
        pwd: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          { min: 6, max: 15, message: '密码长度为6~15个字符', trigger: 'blur' }
        ],
        cpwd: [
          {
            required: true,
            message: '确认密码',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入密码'))
              } else if (value !== this.ruleForm.pwd) {
                callback(new Error('两次输入密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  layout: 'blank',
  methods: {
    sendMsg () {
      // eslint-disable-next-line no-unused-vars
      let namePass, emailPass
      // eslint-disable-next-line no-unused-vars
      // 判断是否已经过去一分钟了
      // eslint-disable-next-line no-console
      console.log(this.timerid)
      if (this.timerid) {
        this.$message({
          message: '验证码已发送，请于一分钟之后再试!',
          type: 'warning'
        })
        return false
      }
      // 验证用户名和邮箱是否为空
      this.$refs.ruleForm.validateField('name', (valid) => {
        namePass = valid
      })
      this.$refs.ruleForm.validateField('email', (valid) => {
        emailPass = valid
      })

      // 先清空状态信息
      this.statusMsg = ''
      if (namePass) {
        // 不合法
        this.$message({
          message: '请输入昵称',
          type: 'warning'
        })
        return false
      }
      if (emailPass) {
        // 不合法
        this.$message({
          message: '请输入邮箱',
          type: 'warning'
        })
        return false
      }
      // 用户名和邮箱都合法
      if (!namePass && !emailPass) {
        // 请求验证码
        this.$axios
          .post('/users/verify', {
            username: encodeURIComponent(this.ruleForm.name),
            email: this.ruleForm.email
          })
          .then(({ status, data }) => {
            if (status === 200 && data && data.code === 0) {
              // 验证码倒计时
              let count = 60
              this.statusMsg = `验证码已发送,剩余${count--}秒`
              // 定时器
              this.timerid = setInterval(() => {
                this.statusMsg = `验证码已发送,剩余${count--}秒`
                if (count === 0) {
                // count为0清除定时器
                  clearInterval(this.timerid)
                  this.timerid = null
                  namePass = null
                  emailPass = null
                  this.statusMsg = ''
                  // eslint-disable-next-line no-console
                  console.log(this.timerid)
                }
              }, 1000)
            } else {
              // 请求失败
              this.statusMsg = data.msg
            }
          })
      }
    },
    register () {
      // 验证表单
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const res = await this.$axios.post('/users/signup', {
            username: encodeURIComponent(this.ruleForm.name),
            password: CryptoJs.MD5(this.ruleForm.pwd).toString(),
            email: this.ruleForm.email,
            code: this.ruleForm.code
          })
          if (status !== 200 && res.data.code !== 0) { return this.$message.warning(res.data.msg) }
          this.$message.success(res.data.msg)
          // 跳转到登陆页面
          setTimeout(() => {
            location.href = '/login'
          }, 1000)
        } else {
          this.$message.error('请确认表单是否已完善！！！')
        }
      })
    }
  }
}
</script>

<style lang="scss">
@import '@/assets/css/register/index.scss';
</style>
